import { useEffect, useMemo } from 'react'
import dayjs from 'dayjs'
import { Button, Card } from 'antd'

import { CusAgGrid } from '@/components/CusAgGrid'
import { UploadWaybillFilesModal } from '@oBiz/TrackOrder/components/UploadWaybillFiles'
import { getFileTypeName, getSourceTypeName } from '@oBiz/TrackOrder/utils'
import { eventBus, popupSlot, useUrlParams } from '../utils'
import { Cell } from './Cell'
import { IAttachmentListItem, TCol } from './interface'
import { useBoundStore } from './store'
import { useAttachmentList } from './useAttachmentList'

export const Attachment = () => {
  useAttachmentList() // 放最顶部
  const { waybillNo } = useUrlParams()

  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const getData = useBoundStore(v => v.getData)

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 130,
      sortable: false,
      cellRenderer: Cell,
    }),
    [],
  )
  const columnDefs = useMemo(
    () => [
      {
        field: 'fileName',
        headerName: '附件名',
        flex: 2,
        minWidth: 210,
      } satisfies TCol<'fileName'>,
      {
        field: 'sourceType',
        headerName: '系统来源',
        flex: 0.01,
        minWidth: 114,
        valueFormatter: ({ value }) => getSourceTypeName(value) || '',
      } satisfies TCol<'sourceType'>,
      {
        field: 'sourceId',
        headerName: '来源单据号',
        minWidth: 128,
      } satisfies TCol<'sourceId'>,
      {
        field: 'fileType',
        headerName: '附件类型',
        flex: 0.01,
        minWidth: 145,
        valueFormatter: ({ value }) => getFileTypeName(value) || '',
      } satisfies TCol<'fileType'>,
      {
        field: 'uploadBy',
        headerName: '上传人',
        flex: 0.01,
        minWidth: 100,
      } satisfies TCol<'uploadBy'>,
      {
        field: 'uploadAt',
        headerName: '上传时间',
        flex: 0.01,
        minWidth: 166,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMDHms) : ''),
      } satisfies TCol<'uploadAt'>,
      {
        field: 'fileId',
        headerName: '操作',
        flex: 0.01,
        width: 100,
        minWidth: 100,
        pinned: 'right',
      } satisfies TCol<'fileId'>,
    ],
    [],
  )

  // 附件变更，如：发布路由所上传的附件、留言所上传/删除的附件
  useEffect(() => eventBus.on('attachmentChanged', () => getData()), [getData])

  // 清理
  useEffect(() => () => useBoundStore.setState(useBoundStore.getInitialState(), true), [])

  return (
    <Card
      styles={{ body: { height: 500 } }}
      title="附件"
      extra={
        <Button
          type="primary"
          onClick={() => {
            const modalUpdate = popupSlot.insert(
              <UploadWaybillFilesModal
                waybillNo={waybillNo}
                destroy={() => modalUpdate(null)}
                onSuccess={() => getData(true)}
              />,
            )
          }}
        >
          上传附件
        </Button>
      }
    >
      <CusAgGrid<IAttachmentListItem>
        loading={loading}
        rowData={data}
        defaultColDef={defaultColDef}
        columnDefs={columnDefs}
        cellSelection={false}
      />
    </Card>
  )
}
